/*
 * $Id$
 */
package py.firefly.tags;

import java.io.IOException;

import java.util.Map;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspWriter;

import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import static py.firefly.resolution.Tiles.*;

import static javax.servlet.jsp.PageContext.*;

/**
 *
 * @author py
 */
public class Tile extends SimpleTagSupport {

    /**
     *      */
    private String _name;
    /**
     *      */
    private String _include;
    /**
     *      */
    private String _value;

    /**
     *
     * @throws IOException
     */
    @Override
    public void doTag() throws IOException {
        final PageContext pc = (PageContext) getJspContext();
        final HttpServletRequest req = (HttpServletRequest) pc.getRequest();
        final JspWriter jw = pc.getOut();
        if (null != _value) {
            jw.write(_value);
        } else if (null != _include) {
            include(_include);
        } else {
            final Object val =
              ((Map<String, Object>) req.getAttribute(TILES)).get(_name);
            if (val instanceof String) {
                final String s = (String) val;
                if (s.endsWith(".jsp") || s.endsWith(".jspx")) {
                    include(s);
                } else {
                    jw.write(s);
                }
            } else if (val != null) {
                jw.write(val.toString());
            }
        }
    }

    /**
     *
     * @param s
     */
    private void include(final String s) {
        final PageContext pc = (PageContext) getJspContext();
        try {
            pc.include(includedPath(s), false);
        } catch (final Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     *
     * @param s
     * @return
     */
    private String includedPath(final String s) {
        if (s.startsWith("/")) {
            return s;
        } else {
            final PageContext pc = (PageContext) getJspContext();
            final String p =
              (String) pc.getAttribute(TILES_TEMPLATE, APPLICATION_SCOPE);
            final int i = p.lastIndexOf("/");
            return new StringBuilder(p.substring(0, i + 1)).append(s).toString();
        }
    }

    /**
     *
     * @param n
     */
    public void setName(final String n) {
        _name = n;
    }

    public void setInclude(final String inc) {
        _include = inc;
    }

    public void setValue(final String val) {
        _value = val;
    }
}
